package com.njd.meitu.tv.main;

import java.io.IOException;
import java.util.ArrayList; 
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.content.Context; 
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log; 
import android.view.Menu;
import android.view.MenuItem;  
import android.view.View;
import android.widget.ArrayAdapter; 
import android.widget.ListPopupWindow;
import android.widget.SpinnerAdapter; 

import com.njd.meitu.tv.R;  
import com.njd.meitu.tv.model.MeiziTuInfo;
import com.njd.meitu.tv.view.XListView;
import com.njd.meitu.tv.view.XListView.IXListViewListener;
import com.njd.meitu.tv.waterfall.Helper; 
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

public class MainActivity extends Activity implements IXListViewListener {
    private XListView mAdapterView = null;
    private StaggeredAdapter mAdapter = null;
    private int currentPage = 1;
    ContentTask task = new ContentTask(this, 2);
    private ListPopupWindow mMenuWindow;
    private MenuAdapter mMenuAdapter;

    
    private class ContentTask extends AsyncTask<String, Integer, List<MeiziTuInfo>> {

        private Context mContext;
        private int mType = 1;

        /**
         * 
         * @param context
         * @param type 1：加载到顶部  2：加载更多到底部
         */
        public ContentTask(Context context, int type) {
            super();
            mContext = context;
            mType = type;
        }

        @Override
        protected List<MeiziTuInfo> doInBackground(String... params) {
            try {
                return parseNewsJSON(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<MeiziTuInfo> result) {
            if (mType == 1) {

                mAdapter.addItemTop(result);
                mAdapter.notifyDataSetChanged();
                mAdapterView.stopRefresh();

            } else if (mType == 2) {
                mAdapterView.stopLoadMore();
                mAdapter.addItemLast(result);
                mAdapter.notifyDataSetChanged();
            }

        }

        @Override
        protected void onPreExecute() {
        }

        public List<MeiziTuInfo> parseNewsJSON(String url) throws IOException {
            List<MeiziTuInfo> duitangs = new ArrayList<MeiziTuInfo>();
            String json = "";
            if (Helper.checkConnection(mContext)) {
                try {
                    json = Helper.getStringFromUrl(url);

                } catch (IOException e) {
                    Log.e("IOException is : ", e.toString());
                    e.printStackTrace();
                    return duitangs;
                }
            }
            Log.d("MainActiivty", "json:" + json);

            try {
                if (null != json) {
                    JSONObject newsObject = new JSONObject(json);
                    JSONObject jsonObject = newsObject.getJSONObject("data");
                    JSONArray meiziTuJson = jsonObject.getJSONArray("list");

                    for (int i = 0; i < meiziTuJson.length(); i++) {
                        JSONObject newsInfoLeftObject = meiziTuJson.getJSONObject(i);
                        MeiziTuInfo meiziTuInfo = new MeiziTuInfo();
                        meiziTuInfo.setTuId(newsInfoLeftObject.getInt("id"));
                        meiziTuInfo.setAlbid(newsInfoLeftObject.isNull("menuId") ? "" : newsInfoLeftObject.getString("menuId"));
                        meiziTuInfo.setIsrc(newsInfoLeftObject.isNull("smallImageUrl") ? "" : newsInfoLeftObject.getString("smallImageUrl"));
                        meiziTuInfo.setMsg(newsInfoLeftObject.isNull("title") ? "" : newsInfoLeftObject.getString("title"));
                        meiziTuInfo.setHeight(newsInfoLeftObject.getInt("picHeight"));
                        duitangs.add(meiziTuInfo);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return duitangs;
        }
    }

    /**
     * 添加内容
     * 
     * @param pageindex
     * @param type
     *            1为下拉刷新 2为加载更多
     */
    private void AddItemToContainer(int pageindex, int type) {
        if (task.getStatus() != Status.RUNNING) {
            String url = "http://mm.sunsharior.com/api/v1/getImagesByCategoryId?pageNum=" + pageindex;
            
            ContentTask task = new ContentTask(this, type);
            task.execute(url);
        }
    }

    

    @SuppressLint("NewApi")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //调用友盟更新
        UmengUpdateAgent.update(this);
        
        setContentView(R.layout.act_pull_to_refresh);
        
        SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, 
                R.array.menu, android.R.layout.simple_spinner_dropdown_item);
         
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setListNavigationCallbacks(adapter, new OnNavigationListener() {
 
            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {

            	return false;
            }
             
        });
        
        mAdapterView = (XListView) findViewById(R.id.list);
        
        mAdapterView.setPullLoadEnable(true);
        mAdapterView.setXListViewListener(this);

        mAdapter = new StaggeredAdapter(this, mAdapterView);
        
        mAdapterView.setAdapter(mAdapter);
        AddItemToContainer(currentPage, 2);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);
		return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
			case R.id.main_menu_today:
				
			break;
			case R.id.main_menu_more:
				showMoreOptionMenu(findViewById(R.id.main_menu_more));
			break;
    	}
	
    	return true;
    }
    
	/**
	 * 更多菜单
	 * @param view
	 */
	private void showMoreOptionMenu(View view) {
		if (mMenuWindow != null) {
			mMenuWindow.dismiss();
			mMenuWindow = null;
		}
		mMenuWindow = new ListPopupWindow(this);
		if (mMenuAdapter == null) {
			mMenuAdapter = new MenuAdapter();
		}
		mMenuWindow.setModal(true);
		mMenuWindow.setContentWidth(getResources().getDimensionPixelSize(
				R.dimen.popo_menu_dialog_width));
		mMenuWindow.setAdapter(mMenuAdapter);
//		mMenuWindow.setOnItemClickListener(this);
		mMenuWindow.setAnchorView(view);
		mMenuWindow.show();
		mMenuWindow.getListView().setDividerHeight(1);
	}

    @Override
    protected void onResume() {
        super.onResume(); 
        
        MobclickAgent.onResume(this);
    }
    
    @Override
    protected void onPause() {    	
    	super.onPause();
    	
    	MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        AddItemToContainer(++currentPage, 1);

    }

    @Override
    public void onLoadMore() {
        AddItemToContainer(++currentPage, 2);

    }
}// end of class
